# -*- coding: utf-8 -*-
# -------------------------------
# @PyCharm：PyCharm 2023.1.3 (Community Edition)
# @Python：Python 3.8.10
# @时间：2024/11/21 21:43
# -------------------------------

import random
from json import loads
from time import strftime

from paho.mqtt import client as mqtt_client

from db import DB
from common import filter_data

broker = 'broker.emqx.io'
port = 1883
topic = "python/iron-refine-data"
# Generate a Client ID with the subscribe prefix.
client_id = f'subscribe-{random.randint(0, 100)}'
# username = 'emqx'
# password = 'public'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    # client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        json_text = msg.payload.decode()
        print(f"Received `{json_text}` from `{msg.topic}` topic")
        dic = loads(json_text)
        dic.update({"ctime": strftime("%Y-%m-%d %H:%M:%S")})
        db_project.write_data(dic, "iron_define_data")
        for alarm_data in filter_data(dic):
            db_project.write_data(alarm_data, "alarm_data")
    client.subscribe(topic)
    client.on_message = on_message


def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()


if __name__ == '__main__':
    db_project = DB()
    run()
